using System;
using System.Collections.Generic;
using System.Data;
using System.Data.SqlClient;
using System.Web.Security;
using System.Configuration;
using Microsoft.SharePoint;
using Microsoft.SharePoint.WebControls;
using Microsoft.SharePoint.Administration;
using System.Web.UI.WebControls;
using System.Reflection;

namespace CKS.FormsBasedAuthentication
{
    public class EditConnections : LayoutsPageBase
    {
        protected InputFormTextBox txtConnectionName;
        protected InputFormTextBox txtConnectionString;
        protected DropDownList ddlConnectionNames;
        protected InputFormSection ifsAdminUser;
        protected InputFormTextBox txtUsername;
        protected InputFormTextBox txtPassword;
        protected InputFormTextBox txtEmail;
        protected InputFormTextBox txtPasswordQuestion;
        protected InputFormTextBox txtPasswordAnswer;
        protected InputFormTextBox txtProviderName;
        protected Button btnDelete;
        protected WebApplicationSelector Selector;
        private Dictionary<string, ConnectionStringSettings> connections;

        protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)
            {
                if (Request.Params["Status"] != string.Empty && Request.Params["Status"] == "Success")
                {
                    RegisterClientScriptBlock("Confirmation", "<script>alert('Your Changes Were Made Successfully');</script>");
                }
            }
        }

        protected void FillConnectionNames()
        {
            try
            {
                ddlConnectionNames.Items.Clear();
                ddlConnectionNames.Items.Add("--New--");
                SPWebApplication web = Selector.CurrentItem;
                connections = new Dictionary<string, ConnectionStringSettings>();
                string path = web.GetResponseUri(SPUrlZone.Default).AbsolutePath;
                System.Configuration.Configuration config = System.Web.Configuration.WebConfigurationManager.OpenWebConfiguration(path);
                foreach (ConnectionStringSettings settings in config.ConnectionStrings.ConnectionStrings)
                {
                    connections.Add(settings.Name, settings);
                }
                foreach (SPWebConfigModification mods in web.WebConfigModifications)
                {
                    if (mods.Path == "configuration/connectionString")
                    {
                        ConnectionStringSettings setting = new ConnectionStringSettings();
                        string[] words = mods.Value.Split(' ');
                        for (int idx = 0; idx < words.Length; idx++)
                        {
                            if (words[idx].Contains("name="))
                                setting.Name = words[idx].Replace("name=\"", "").Replace("\"", "");
                            if (words[idx].Contains("providerName="))
                                setting.ProviderName = words[idx].Replace("providerName=\"", "").Replace("\"", "");
                            if (words[idx].Contains("connectionString="))
                                setting.ConnectionString = words[idx].Replace("connectionString=\"", "").Replace("\"", "");
                        }
                        connections.Add(setting.Name, setting);
                    }
                }
                foreach(ConnectionStringSettings setting in connections.Values)
                {
                    ddlConnectionNames.Items.Add(setting.Name);
                }
            }
            catch (Exception ex)
            {
                TraceProvider.WriteTrace(0, TraceProvider.TraceSeverity.CriticalEvent, Guid.NewGuid(), Assembly.GetExecutingAssembly().FullName, "CKS.FormsBasedAuthentication", "EditConnections", ex.Message);
            }
        }

        protected void Selector_OnContextChange(object sender, EventArgs e)
        {
            FillConnectionNames();
            ddlConnectionNames_SelectedIndexChanged(ddlConnectionNames, EventArgs.Empty);
        }

        protected void ddlConnectionNames_SelectedIndexChanged(object sender, EventArgs e)
        {
            if (ddlConnectionNames.SelectedValue == "--New--")
            {
                txtConnectionName.Text = "NewConnection";
                txtProviderName.Text = "System.Data.SqlClient";
                txtConnectionName.Enabled = true;
                btnDelete.Enabled = false;
            }
            else
            {
                txtConnectionName.Enabled = false;
                LoadConnectionInfo(ddlConnectionNames.SelectedValue);
                btnDelete.Enabled = true;
            }
        }

        private void LoadConnectionInfo(string ConnectionName)
        {

            txtConnectionName.Text = connections[ConnectionName].Name;
            txtConnectionString.Text = connections[ConnectionName].ConnectionString;
            txtProviderName.Text = connections[ConnectionName].ProviderName;
        }

        protected void OnSubmit(object sender, EventArgs e)
        {
            try
            {
                SPWebApplication webApp = SPWebService.ContentService.WebApplications[Selector.CurrentItem.Id];
                if (ddlConnectionNames.SelectedValue != "--New--")
                {
                    foreach (SPWebConfigModification mod in webApp.WebConfigModifications)
                    {
                        if (mod.Name == "MP." + ddlConnectionNames.SelectedValue)
                        {
                            mod.Value = String.Format("<add name=\"{0}\" connectionString=\"{1}\" providerName=\"{2}\" />", ddlConnectionNames.SelectedValue, txtConnectionString.Text, txtProviderName.Text);
                        }
                    }
                }
                else
                {
                    SPWebConfigModification mod = new SPWebConfigModification("MP." + txtConnectionName.Text, "configuration/connectionStrings");
                    mod.Owner = "FBAConfigManagement";
                    mod.Type = SPWebConfigModification.SPWebConfigModificationType.EnsureChildNode;
                    mod.Value = String.Format("<add name=\"{0}\" connectionString=\"{1}\" providerName=\"{2}\" />", txtConnectionName.Text, txtConnectionString.Text, txtProviderName.Text);
                    webApp.WebConfigModifications.Add(mod);
                }
                SPFarm.Local.Services.GetValue<SPWebService>().ApplyWebConfigModifications();
                webApp.Update();
                Response.Redirect(Request.Url.ToString() + "?Status=Success");
            }
            catch (Exception ex)
            {
                TraceProvider.WriteTrace(0, TraceProvider.TraceSeverity.CriticalEvent, Guid.NewGuid(), Assembly.GetExecutingAssembly().FullName, "CKS.FormsBasedAuthentication", "EditConnections", ex.Message);
            }
        }

        protected void DeleteConnection(object sender, EventArgs e)
        {
            SPWebApplication webApp = SPWebService.ContentService.WebApplications[Selector.CurrentId];
            foreach (SPWebConfigModification mod in webApp.WebConfigModifications)
            {
                if (mod.Name == "MP." + ddlConnectionNames.SelectedValue)
                {
                    webApp.WebConfigModifications.Remove(mod);
                    SPFarm.Local.Services.GetValue<SPWebService>().ApplyWebConfigModifications();
                    webApp.Update();
                }
            }
        }

        private void SetupDatabase(System.Configuration.Configuration config)
        {
            //int tableInstalled = 0;

            ////Save Connection Details
            //if (System.Configuration.ConfigurationManager.ConnectionStrings[txtConnectionStringName.Text] == null)
            //{
            //    //New Connection Setting - add to web.config
            //    config.ConnectionStrings.ConnectionStrings.Add(new System.Configuration.ConnectionStringSettings(txtConnectionStringName.Text, txtConnectionString.Text));
            //}
            //else
            //{
            //    //Existing Connection String - update connection string
            //    config.ConnectionStrings.ConnectionStrings[txtConnectionStringName.Text].ConnectionString = txtConnectionString.Text;
            //}
            ////Check to see if the membership tables are already setup
            //SqlConnection conn = new System.Data.SqlClient.SqlConnection(txtConnectionString.Text);
            //try
            //{
            //    conn.Open();
            //    SqlCommand cmd = new SqlCommand("IF EXISTS (SELECT 1 FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_TYPE='BASE TABLE' AND TABLE_NAME='aspnet_Membership') SELECT 1 ELSE SELECT 0", conn);
            //    tableInstalled = (int)cmd.ExecuteScalar();
            //    conn.Close();
            //}
            //catch (SqlException ex)
            //{
            //    if (ex.ErrorCode != 2146232060)
            //        throw ex;
            //}
            //finally
            //{
            //    if (conn.State != ConnectionState.Closed)
            //        conn.Close();
            //}
            //if (tableInstalled == 0)
            //{
            //    try
            //    {
            //        //Tables Not Installed - Add It
            //        System.Web.Management.SqlServices.Install(conn.DataSource, conn.Database == null ? "aspnetdb" : conn.Database, System.Web.Management.SqlFeatures.Membership | System.Web.Management.SqlFeatures.RoleManager);
            //        //Add Application
            //        //SqlCommand addAppCmd = new SqlCommand("aspnet_Applications_CreateApplication", conn);
            //        //addAppCmd.Parameters.Add(new SqlParameter("@ApplicationName", txtApplicationName.Text));
            //        //addAppCmd.Parameters.Add("@ApplicationId", SqlDbType.UniqueIdentifier);
            //        //addAppCmd.Parameters["@ApplicationId"].Direction = ParameterDirection.Output;
            //        //conn.Open();
            //        //addAppCmd.ExecuteNonQuery();
            //        //conn.Close();
            //        //Seed Admin User
            //        //SqlCommand addUserCmd = new SqlCommand("aspnet_Membership_CreateUser", conn);
            //        //addUserCmd.Parameters.Add(new SqlParameter("@ApplicationName", txtApplicationName.Text));
            //        //addAppCmd.Parameters.Add(new SqlParameter("@UserName", "Administrator"));
            //        //addAppCmd.Parameters.Add(new SqlParameter("@Password", "p@ssword"));
            //        //addAppCmd.Parameters.Add(new SqlParameter("@PasswordSalt", Guid.NewGuid().ToString()));
            //        //addAppCmd.Parameters.Add(new SqlParameter("@Email", "p@ssword"));
            //    }
            //    finally
            //    {
            //        if (conn.State != ConnectionState.Closed)
            //            conn.Close();
            //    }

            //}
        }
    }
}
